package com.tensquare.article.service;

import com.tensquare.article.dao.ArticleDao;
import com.tensquare.article.pojo.Article;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.Optional;
import java.util.concurrent.TimeUnit;


@Service
@Transactional
public class ArticleService {
    @Autowired
    private ArticleDao articleDao;
    @Autowired
    private RedisTemplate redisTemplate;
    //1.审核文章
    public void examine(String articleId) {
        articleDao.examine(articleId);
    }
    //2.文章点赞
    public void thumbup(String articleId) {
        articleDao.thumbup(articleId);
    }
    //3.使用redis--findById
    public Article findById(String id){
        Article article = (Article) redisTemplate.opsForValue().get("article_" + id);
        if (article==null){
            article= articleDao.findById(id).get();
            redisTemplate.opsForValue().set("article_"+id,article,10, TimeUnit.MINUTES);
        }
        return article;
    }
    //4.修改文章时清空缓存
    public void update(Article article){
        redisTemplate.delete("article"+article.getId());
        articleDao.save(article);
    }
    //5.删除文章时清空缓存
    public void delete(String id){
        redisTemplate.delete("article"+id);
        articleDao.deleteById(id);
    }
}

